﻿
using Xacml.Core.Interfaces;
using Xacml.Core.Runtime;
using System.Xml;

namespace Xacml.Core.Runtime.Functions
{
  public class XPathNodeCount : FunctionBase
  {
    public override string Id
    {
      get
      {
        return "urn:oasis:names:tc:xacml:1.0:function:anyURI-equal";
      }
    }

    public override IDataType Returns
    {
      get
      {
        return (IDataType) DataTypeDescriptor.Integer;
      }
    }

    public override IDataType[] Arguments
    {
      get
      {
        return new IDataType[1]
        {
          (IDataType) DataTypeDescriptor.String
        };
      }
    }

    public override EvaluationValue Evaluate(EvaluationContext context, params IFunctionParameter[] args)
    {
      XmlDocument xmlDocument = context.ContextDocument.XmlDocument;
      if (context.ContextDocument.XmlNamespaceManager == null)
        context.ContextDocument.AddNamespaces(context.PolicyDocument.Namespaces);
      string stringArgument = this.GetStringArgument(args, 0);
      return new EvaluationValue((object) xmlDocument.DocumentElement.SelectNodes(stringArgument, context.ContextDocument.XmlNamespaceManager).Count, (IDataType) DataTypeDescriptor.Integer);
    }
  }
}
